<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Fees Extends MY_Controller
{
	private $auth_to_update_fees;
	private $current_session_user;
	public function __construct()
	{
		parent::__construct();
		//laod acl_config
		$this->config->load('acl_config');
		$this->page_auth->secure_page($this->config->item('auth_link_to_view_fees'));
		$this->auth_to_update_fees = $this->config->item('auth_to_update_fees');
		$this->current_session_user = strtolower($this->session->userdata('userType'));
		$this->load->model(array('M_school_years','M_enrollees','M_gperiods','M_student_payment_record','M_fees','M_penalty_assessments','M_payment_mode_value','M_sections','M_student','M_payee'));
		$this->load->helper('misc');
		$this->_set_config_items();
		$this->view_data['system_message'] = $this->_msg();
		
		$this->view_data['months'] = 
				array(''=>'-- Choose Month --',
				   'Registration'=>'Registration',
				   'January'=>'January',
				   'February'=>'February',
				   'March'=>'March',
				   'April'=>'April',
				   'May'=>'May',
				   'June'=>'June',
				   'July'=>'July',
				   'August'=>'August',
				   'September'=>'September',
				   'October'=>'October',
				   'November'=>'November',
				   'December'=>'December');

	}
	
	public function view_fees($e_id='')
	{
		if(is_numeric($e_id) AND $this->M_enrollees->check_enrollment_id($e_id))
		{
			$this->view_data['official_student'] = TRUE;
			
			$this->load->model(array('M_enrollees','M_scholarships','M_fees','M_assessment_fees','M_applicants','M_payment_mode_value'));
			
			//token
			$this->load->library('token');
			$this->token->set_token();
			$this->view_data['token'] = $this->token->get_token();
			
			$this->view_data['payment_mode'] = $this->M_enrollees->get_student_payment_mode($e_id);
			$this->view_data['authlink'] = $this->authlink->generate_authlink();
			$this->view_data['student_deductions'] = $this->M_scholarships->get_student_deductions($e_id);
			$this->view_data['available_deductions'] = $this->M_scholarships->get_available_deductions($e_id);
			$this->view_data['student_scholarships'] = $this->M_scholarships->get_student_scholarships_deducted($e_id);
			$this->view_data['total_stud_deductions'] = $this->M_scholarships->sum_all_student_deductions($e_id);
			$this->view_data['system_message'] = $this->session->flashdata('system_message');
			
			$this->view_data['tuit_fees'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'tuit');
			$this->view_data['cca_fees'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'cca');
			$this->view_data['misc_fees'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'misc');
			$this->view_data['other_fees'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'other');
			//$this->view_data['uniform'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'uniform');
			
			$this->view_data['otcp'] = $this->M_enrollees->get_otcp($e_id);
			
			$this->view_data['af'] = $this->M_assessment_fees->get_assessment_fee($e_id);
			
			$this->view_data['modal']['scholarships'] = $this->M_scholarships->get_scholarships_available_for_stud($e_id);
			$this->view_data['modal']['payment_value'] = $this->M_enrollees->get_student_payment_mode($e_id);
			$this->view_data['modal']['student_payment_schedule'] = $this->M_payment_mode_value->get_student_payment_schedule($e_id);
			$this->view_data['modal']['misc_fees_for_modal'] = $this->M_enrollees->get_sum_of_student_miscelaneous($e_id);
			$this->view_data['modal']['other_fees_for_modal'] = $this->M_enrollees->get_sum_of_student_electives($e_id);
			$this->view_data['modal']['id'] = $e_id;
			
			$this->view_data['enrollee_data'] = $enrollee_data = $this->M_enrollees->get_enrollee_prof($e_id);
			$this->view_data['sum_paid_fees'] = $this->M_enrollees->get_sum_of_paid_fees($e_id,$this->current_school_year);
			$this->view_data['sum_amount_due'] = $this->M_enrollees->get_sum_of_amount_due($e_id,$this->current_school_year);
			$this->view_data['profile_id'] = NULL;
			$this->view_data['enrollment_id'] = $e_id;
			$this->view_data['level_id'] = $enrollee_data->level_id;
			$this->view_data['enrollee_type'] = $enrollee_data->e_enrollee_type;
			$this->view_data['guidance_recommendation'] = $this->M_applicants->get_applicant($e_id);
			
			$payment_data['amount_due'] = $this->view_data['sum_amount_due'];
			$payment_data['amount_paid'] = $this->view_data['sum_paid_fees'];
			
			if((!empty($payment_data['amount_due']) AND !empty($payment_data['amount_paid'])) AND ($payment_data['amount_due'] - $payment_data['amount_paid']) == 0)
			{
				$this->M_student_payment_record->update_fully_paid_status($e_id);
				$this->view_data['finance_status'] = $this->_msg('n','Student is already full paid.');
			}
			
			
			$this->session->set_userdata('payment_data','');
			$this->session->set_userdata('payment_data',(object)$payment_data);
			
			if(in_array($this->current_session_user,$this->auth_to_update_fees))
			{
				$this->view_data['menu_true'] = TRUE;
				$this->view_data['add_edit_deductions'] =function($a,$auth){return '<a href="" data-reveal-id="main-modal-menu" class="btn btn-mini btn-success">Add</a>';};
				$this->view_data['delete_link'] = function($a,$b,$c){return'<td><a href="'.site_url('fees/delete_stud_fee/'.$a.'/'.$b.'/'.$c).'" class="btn btn-mini btn-danger confirm" title="Are you sure you want to delete fee from record? Changes cannot be reverted."><i class="icon-remove"></i></a></td>';};
			}else{
				$this->view_data['menu_true'] = FALSE;
				$this->view_data['add_edit_deductions'] = function(){return NULL;};
				$this->view_data['delete_link'] = function(){return '<td>&nbsp;</td>';};
			}
			
			if($this->input->post('add_penalty_assessment'))
			{
				$input['amount'] = $this->input->post('password');
				$input['enrollment_id'] = $e_id;
				$input['schoolyear_id'] = $this->current_school_year;// defined in mycontroller
				if($this->M_penalty_assessments->add_penalty_assessment($input) == TRUE)
				{
				
					$c_spr_id = $this->M_student_payment_record->current_payment_record_id($e_id_post);
					
					$counter =0;
					
						$data[$counter]['sef_fee_name'] = 'Assessment Charge as of '.NOW;
						$data[$counter]['sef_fee_rate'] = $this->input->post('password');
						$data[$counter]['sef_enrollment_id'] = $e_id;
						$data[$counter]['sef_gperiod_id'] = $this->current_grading_period;
						$data[$counter]['sef_schoolyear_id'] = $this->current_school_year;
						$data[$counter]['sef_created'] =NOW;
						$data[$counter]['is_other_fee'] = 1;
							
						if($c_spr_id !== NULL)
						{
							$for_pb[$counter]['spb_fee_name'] = 'Assessment Charge as of '.NOW;
							$for_pb[$counter]['spb_remaining_balance'] = $this->input->post('password');
							$for_pb[$counter]['spb_fee_rate'] = $this->input->post('password');
							$for_pb[$counter]['spb_transacted_by'] =$this->session->userdata('userid');
							$for_pb[$counter]['spb_spr_id'] =$c_spr_id;
							$for_pb[$counter]['spb_created'] =NOW;
							$for_pb[$counter]['spb_stud_enrollment_id'] = $e_id;
							$for_pb[$counter]['spb_is_other_fee'] = 1;
						}else{
							$for_pb = FALSE;
						}		
					
					if($this->M_enrollees->cashier_add_new_fees($data,$for_pb) == TRUE){
						$this->authlink->clear_authlink();
						$this->_msg('s','Penalty Assessment has been added.','fees/view_fees/'.$e_id);
					}else{
						$this->authlink->clear_authlink();
						$this->_msg('e','System Error. Please try again.','fees/view_fees/'.$e_id);
					}
				}else{
					$this->authlink->clear_authlink();
					$this->_msg('e','System Error. Please try again.','fees/view_fees/'.$e_id);
				}
			}
			
			if($this->input->post('add_guidance_recommendation'))
			{
				$input['amount'] = $this->input->post('password');
				$input['enrollment_id'] = $e_id;
				$input['schoolyear_id'] = $this->current_school_year;// defined in mycontroller
				if($this->M_penalty_assessments->add_penalty_assessment($input) == TRUE)
				{
				
					$c_spr_id = $this->M_student_payment_record->current_payment_record_id($e_id_post);
					
					$counter =0;
					
						$data[$counter]['sef_fee_name'] = $this->input->post('fee_name');
						$data[$counter]['sef_fee_rate'] = $this->input->post('password');
						$data[$counter]['sef_enrollment_id'] = $e_id;
						$data[$counter]['sef_gperiod_id'] = $this->current_grading_period;
						$data[$counter]['sef_schoolyear_id'] = $this->current_school_year;
						$data[$counter]['sef_created'] =NOW;
						$data[$counter]['is_other_fee'] = 1;
							
						if($c_spr_id !== NULL)
						{
							$for_pb[$counter]['spb_fee_name'] = $this->input->post('fee_name');
							$for_pb[$counter]['spb_remaining_balance'] = $this->input->post('password');
							$for_pb[$counter]['spb_fee_rate'] = $this->input->post('password');
							$for_pb[$counter]['spb_transacted_by'] =$this->session->userdata('userid');
							$for_pb[$counter]['spb_spr_id'] =$c_spr_id;
							$for_pb[$counter]['spb_created'] =NOW;
							$for_pb[$counter]['spb_stud_enrollment_id'] = $e_id;
							$for_pb[$counter]['spb_is_other_fee'] = 1;
						}else{
							$for_pb = FALSE;
						}		
					
					if($this->M_enrollees->cashier_add_new_fees($data,$for_pb) == TRUE){
						$this->authlink->clear_authlink();
						$this->_msg('s','Fee has been added.','fees/view_fees/'.$e_id);
					}else{
						$this->authlink->clear_authlink();
						$this->_msg('e','System Error. Please try again.','fees/view_fees/'.$e_id);
					}
				}else{
					$this->authlink->clear_authlink();
					$this->_msg('e','System Error. Please try again.','fees/view_fees/'.$e_id);
				}
			}
			
			if($this->input->post('add_deduction'))
			{
				$this->form_validation->set_rules('deduction_rate','Deduction Rate','trim|numeric|required');
				$this->form_validation->set_rules('deduction_desc','Deduction Description','trim|strtolower');
				
				if($this->form_validation->run() !== FALSE)
				{
					$post['deduction_rate'] = $this->input->post('deduction_rate');
					if($this->input->post('deduction_desc')){
						$post['deduction_desc'] = $this->input->post('deduction_desc');
					}elseif($this->input->post('deduction_desc2')){
						$post['deduction_desc'] = $this->input->post('deduction_desc2');
					}else{
						$this->form_validation->set_rules('deduction_desc','Deduction Description','trim|strtolower|required');
					}
					
					if($this->form_validation->run() !== FALSE)
					{
						$result = $this->_process_student_deduction($e_id,$post);

						if($result->stat == TRUE)
						{
							$fname = $this->session->userdata('e_f_name');
							$lname = $this->session->userdata('e_l_name');
							$this->logger('log','User: {'.$fname.' '.$lname.'}, successfully add deduction for enrollment id {'.$e_id.'}.');
							
							$this->_msg('s',$result->log,'fees/view_fees/'.$e_id);
						}else{
						
							$fname = $this->session->userdata('e_f_name');
							$lname = $this->session->userdata('e_l_name');
							$this->logger('log','User: {'.$fname.' '.$lname.'}, failed to add deduction for enrollment id {'.$e_id.'}.');
							
							$this->_msg('e',$result->log,'fees/view_fees/'.$e_id);
						}
					}
				}else{
					$this->view_data['system_message'] = validation_errors() == '' ? NULL : $this->_msg('e',validation_errors()); 
				}
			}
			
			//process students scholarships
			if($this->input->post('add_scholarship'))
			{
				$scholarship_id = $this->input->post('scholarship_id');

				if($scholarship_id)
				{
					$result = $this->_process_student_scholarship($e_id,$scholarship_id);

					if($result->status == TRUE)
					{
						$this->_msg('s',$result->message,'fees/view_fees/'.$e_id);
					}else{
						$this->_msg('e',$result->message,'fees/view_fees/'.$e_id);
					}
				}else{
					$this->_msg('e','Cannot Process Empty scholarship. Please select a scholarship package to apply to student.','fees/view_fees/'.$e_id);
				}
			}
			
			$this->view_data['add_uniform'] = $this->M_fees->get_fee_array('uniform');
			
			//Assessment Fee payment process
			if($this->input->post('assessment_fee'))
			{
				$input['user_trans_id'] = $this->session->userdata('userid');
				$input['user_trans_name'] = $this->session->userdata('username');
				$input['enrollment_id'] = $e_id;
				$input['or_no'] = $this->input->post('spr_or_no');
				$input['remarks'] = 'Assessment Fee';
				$input['remarks'] = $this->input->post('desc');
				$input['payment_date'] =  date('Y-m-d',strtotime($this->input->post('date_of_payment')));
				$input['schoolyear_id'] = $this->current_school_year;// defined in mycontroller
				$input['gperiod_id'] = $this->current_grading_period;// defined in mycontroller
				$input['ammt_paid'] = $this->input->post('price');
				$input['created'] = NOW;
				
				$hear_from = array();
				if($this->input->post('billboard') == 'yes')
				{
					array_push($hear_from,'Billboard');
				}
				
				if($this->input->post('signs_brochures') == 'yes')
				{
					array_push($hear_from,'Signs/Brochures');
				}
				
				if($this->input->post('driving_by') == 'yes')
				{
					array_push($hear_from,'Driving By');
				}
				
				if($this->input->post('friends_relatives') == 'yes')
				{
					array_push($hear_from,'Friends/Relatives');
				}
				
				if($this->input->post('website') == 'yes')
				{
					array_push($hear_from,'Website');
				}
				
				if($this->input->post('bluebook') == 'yes')
				{
					array_push($hear_from,'Bluebook');
				}
				
				if($this->input->post('facebook') == 'yes')
				{
					array_push($hear_from,'Facebook');
				}
				
				if($this->input->post('malls') == 'yes')
				{
					array_push($hear_from,'Malls');
				}
				
				if($this->input->post('others') == 'yes')
				{
					array_push($hear_from,'Others');
				}
				
				if($this->input->post('for_others') == 'yes')
				{
					array_push($hear_from,'Others');
					array_push($hear_from,$this->input->post('for_others'));
				}
				
				$hear = '';
				$ctr = 0;
				foreach($hear_from as $k=>$v)
				{
					$ctr++;
					$hear .= $v;
					if($ctr < count($hear_from))
					{
						$hear .= ', ';
					}
				}

				$data['hear_from'] = $hear;
				$data['schedule_for_testing'] = $this->input->post('schedule_for_testing');
				
				if($this->M_student_payment_record->assessment_fee($input) == TRUE)
				{
					$this->db->update('enrollments', $data, array("e_id" => $e_id));
					
					$this->authlink->clear_authlink();
					$this->_msg('s','Payment transaction has been recorded.','fees/view_fees/'.$e_id);
				}else{
					$this->authlink->clear_authlink();
					$this->_msg('e','System Error. Please try again.','fees/view_fees/'.$e_id);
				}
	
			}
			
			if($this->input->post('update_payment_plan'))
			{
				$input['payment_mode_value'] = $this->input->post('plan_value');
				
				if($this->M_enrollees->update_payment_plan_value($e_id,$input) == TRUE)
				{
					$this->_msg('s','Payment transaction has been recorded.','fees/view_fees/'.$e_id);
				}else{
					$this->_msg('e','System Error. Please try again.','fees/view_fees/'.$e_id);
				}
			}
		}else{
			$this->view_data['official_student'] = FALSE;
		}
		
		if($this->input->post('go_to_student'))
		{
			$student = $this->input->post('student_search_data',TRUE);


			$c_eid = $this->input->post('current_student') ? $this->input->post('current_student',TRUE) : 0;
			$f_student = strpos($student,'-') > 0 ? explode('-',$student) : FALSE;
			if($f_student)
			{
				$this->_msg('n','Student ('.ucwords(strtolower($f_student[1])).') found','fees/view_fees/'.$f_student[0]);
			}else{
				$this->_msg('n','No student','fees/view_fees/');
			}
		}
	}
	
	public function check_pull_tuition_fee($e_id,$a)
	{
		if(is_numeric($e_id))
		{	
			$e_id = intval($e_id);
			
			if($this->authlink->verify_authlink($a))
			{
				$this->load->model('M_level_fees','mlf');
				$this->load->model('M_enrollees','e');
				$this->load->model('M_new_enrollee','n');
				
				$data = $this->e->get_enrollee_prof($e_id);
				
				if($data !== FALSE)
				{
					$tuition_fees = $this->mlf->get_tuition_fees_set_for_current_level($data->level_id);
					if($tuition_fees !== FALSE)
					{	
						if($this->n->set_tuition_fees_set_for_current_level($tuition_fees,$data->level_id,$e_id,$this->current_grading_period,$this->current_school_year) == TRUE)
						{
							$this->authlink->clear_authlink();
							$this->_msg('s','Tuition successfully added to student account details.','fees/view_fees/'.$e_id);
						}else{
							$this->authlink->clear_authlink();
							$this->_msg('e','System encountered an Error while adding Miscellaneous Fees to student account details.','fees/view_fees/'.$e_id);
						}		
					}else{
						$this->authlink->clear_authlink();
						$this->_msg('e','Please contact system administrator. Tuition fees for '.ucwords($data->level_desc).' has not been set.','fees/view_fees/'.$e_id);
					}
				}else{
					$this->authlink->clear_authlink();
					$this->_msg('e','Error! Missing student credentials on the system.','fees/view_fees/'.$e_id);
				}
			}else{
				redirect($this->current_session_user);
			}
		}
	}
	
	public function check_pull_cca_fee($e_id,$a)
	{
		if(is_numeric($e_id))
		{	
			$e_id = intval($e_id);
			
			// vd($this->authlink->verify_authlink($a));
			
			
			if($this->authlink->verify_authlink($a))
			{
				$this->load->model('M_level_fees','mlf');
				$this->load->model('M_enrollees','e');
				$this->load->model('M_new_enrollee','n');
				
				$data = $this->e->get_enrollee_prof($e_id);
				
				$enrolle_type = $data->e_enrollee_type;
				if($enrolle_type == 'new'){
					$for_new = 'yes';
				}else{
					$for_new = 'no';
				}
				
				if($data !== FALSE)
				{
					if($this->n->_insert_matriculation_fee($e_id,$data->level_id,$for_new) === TRUE)
					{
						$this->authlink->clear_authlink();
						$this->_msg('s','Process was successful. Added Matriculation Fees to student account details.','fees/view_fees/'.$e_id);
					}else{
						$this->authlink->clear_authlink();
						$this->_msg('e','System encountered an error while adding Matriculation Fees to student account details.','fees/view_fees/'.$e_id);
					}
				}else{
					$this->authlink->clear_authlink();
					$this->_msg('e','Error! Missing student credentials on the system.','fees/view_fees/'.$e_id);
				}
			}else{
				redirect($this->current_session_user);
			}
		}
	}
	
	public function check_pull_miscellaneous_fee($e_id,$a)
	{
		if(is_numeric($e_id))
		{	
			$e_id = intval($e_id);
			
			if($this->authlink->verify_authlink($a))
			{
				$this->load->model('M_level_fees','mlf');
				$this->load->model('M_enrollees','e');
				$this->load->model('M_new_enrollee','n');
				$data = $this->e->get_enrollee_prof($e_id);
				
				if($data !== FALSE)
				{
					$misc_fees = $this->mlf->get_misc_fees($e_id);
					if($misc_fees !== FALSE)
					{	
						if($this->n->_insert_miscellaneous_fee($misc_fees,$e_id,$this->current_school_year) == TRUE)
						{
							$this->authlink->clear_authlink();
							$this->_msg('s','Miscellaneous Fees are successfully added to student account details.','fees/view_fees/'.$e_id);
						}else{
							$this->authlink->clear_authlink();
							$this->_msg('e','System Errorm. cannot add Miscellaneous Fee to student details.','fees/view_fees/'.$e_id);
						}		
					}else{
						$this->authlink->clear_authlink();
						$this->_msg('e','Please contact system administrator. Miscellaneous fees for '.ucwords($data->level_desc).' has not been set.','fees/view_fees/'.$e_id);
					}
				}else{
					$this->authlink->clear_authlink();
					$this->_msg('e','Error! Missing student credentials on the system.','fees/view_fees/'.$e_id);
				}
			}else{
				redirect($this->current_session_user);
			}
		}
	}
	
	public function generate_student_fees($e_id)
	{
		$x = $this->hs->decrypt($e_id);
		if($x)
		{	
			$id = $x[0];
			
			$this->load->model('M_level_fees','mlf');
			
			$res = $this->mlf->generate_student_fees($id);
			if($res->stat == 'true')
			{
				$this->_msg('s',$res->log,'fees/view_fees/'.$id);
			}else{
				$this->_msg('e',$res->log,'fees/view_fees/'.$id);
			}
		}
	}
	
	public function payment_record($id = FALSE,$pid = FALSE)
	{
		$this->disable_browser_cache = TRUE;
		if(is_numeric($id) AND $id !== FALSE)
		{	
			$this->load->model('M_student_payment_record','mspr');
			$this->view_data['payments_made'] = $this->mspr->get_payment_record_by_enrollment_id($id);
			if(!empty($this->view_data['payments_made']))
			{
				$this->view_data['system_message'] = $this->session->flashdata('system_message');
				$this->view_data['authlink'] = $this->authlink->generate_authlink();
				$id = intval($id);
				$this->view_data['enrollee_data'] = $this->M_enrollees->get_enrollee_prof($id);
				$this->view_data['enrollment_id'] = $id;
				$this->view_data['rdate'] = function($x){return date('M d, Y h:i A',strtotime($x));};
				
				if(is_numeric($pid))
				{
					$this->load->model('M_student_payment_breakdown','mspb');
					$this->view_data['payment_breakdown'] = $this->mspb->get_payment_breakdown_by_spr_id($pid);
					$this->view_data['payment_breakdown_id'] = $pid;
				}
			}else{
				$this->_msg('n','Student has no payment record yet.','fees/view_fees/'.$id);
			}
		}else{
			redirect($this->current_session_user);
		}
	}
	
	public function add_fee($enrollment_id = FALSE)
	{
		if($enrollment_id == FALSE)
		{
			if($this->input->post('cashier_add_fee') == FALSE){
				redirect($this->current_session_user);
			}else{
				$enrollment_id_post = $this->input->post('enrollment_id',TRUE);
				$c_spr_id = $this->M_student_payment_record->current_payment_record_id($enrollment_id_post);
					
				$counter =0;
				foreach($this->input->post('fee') as $key => $value)
				{
					foreach($value as $rate => $name)
					{
						$data[$counter]['sef_fee_name'] = $name;
						$data[$counter]['sef_fee_rate'] = $rate;
						$data[$counter]['sef_enrollment_id'] = $enrollment_id_post;
						$data[$counter]['sef_gperiod_id'] = $this->current_grading_period;
						$data[$counter]['sef_schoolyear_id'] = $this->current_school_year;
						$data[$counter]['sef_created'] =NOW;
						$data[$counter]['is_misc_fee'] = 1;
							
						if($c_spr_id !== NULL)
						{
								$for_pb[$counter]['spb_fee_name'] =$name;
								$for_pb[$counter]['spb_remaining_balance'] = $rate;
								$for_pb[$counter]['spb_fee_rate'] =$rate;
								$for_pb[$counter]['spb_transacted_by'] =$this->session->userdata('userid');
								$for_pb[$counter]['spb_spr_id'] =$c_spr_id;
								$for_pb[$counter]['spb_created'] = NOW;
								$for_pb[$counter]['spb_stud_enrollment_id'] = $enrollment_id_post;
								$for_pb[$counter]['spb_is_misc_fee'] = 1;
						}else{
							$for_pb = FALSE;
						}
						$counter++;
					}
				}
				
				if($this->M_enrollees->cashier_add_new_fees($data,$for_pb) == TRUE){
					$this->_msg('s','Successfully added miscellaneous fee to student account details. ','fees/view_fees/'.$enrollment_id_post);
				}else{
					$this->_msg('e','System encountered an error while adding other fee to student. ','fees/view_fees/'.$enrollment_id_post);
				}
			}
			
		}elseif(is_numeric($enrollment_id)){
		
			$this->view_data['available_fees'] = $this->M_enrollees->get_available_fees($enrollment_id);
			$this->view_data['enrollment_id'] = $enrollment_id;
			
		}
	}
	
	public function add_elective_fee($enrollment_id = FALSE)
	{
		if($enrollment_id == FALSE)
		{
			if($this->input->post('cashier_add_efee') == FALSE)
			{
				redirect($this->current_session_user);
			}else
			{
				$enrollment_id_post = $this->input->post('enrollment_id',TRUE);
				$c_spr_id = $this->M_student_payment_record->current_payment_record_id($enrollment_id_post);
					
				$counter =0;
				foreach($this->input->post('fee') as $key => $value)
				{
					foreach($value as $rate => $name)
					{
						$data[$counter]['sef_fee_name'] = $name;
						$data[$counter]['sef_fee_rate'] = $rate;
						$data[$counter]['sef_enrollment_id'] = $enrollment_id_post;
						$data[$counter]['sef_gperiod_id'] = $this->current_grading_period;
						$data[$counter]['sef_schoolyear_id'] = $this->current_school_year;
						$data[$counter]['sef_created'] =NOW;
						$data[$counter]['is_elective_fee'] = 1;
							
						if($c_spr_id !== NULL)
						{
								$for_pb[$counter]['spb_fee_name'] =$name;
								$for_pb[$counter]['spb_remaining_balance'] = $rate;
								$for_pb[$counter]['spb_fee_rate'] =$rate;
								$for_pb[$counter]['spb_transacted_by'] =$this->session->userdata('userid');
								$for_pb[$counter]['spb_spr_id'] =$c_spr_id;
								$for_pb[$counter]['spb_created'] = NOW;
								$for_pb[$counter]['spb_stud_enrollment_id'] = $enrollment_id_post;
								$for_pb[$counter]['is_elective_fee'] = 1;
						}else{
							$for_pb = FALSE;
						}
						$counter++;
					}
				}
				
				if($this->M_enrollees->cashier_add_new_efees($data,$for_pb) == TRUE){
					$this->_msg('s','Elective fee was added to student account details.','fees/view_fees/'.$enrollment_id_post);
				}else{
					$this->_msg('e','Error. Elective fee was not added to student account details.','fees/view_fees/'.$enrollment_id_post);
				}
			}
			
		}elseif(is_numeric($enrollment_id))
		{
			$this->view_data['available_fees'] = $this->M_enrollees->get_elective_fees($enrollment_id);
			$this->view_data['enrollment_id'] = $enrollment_id;
		}
	}
	
	
	
	
	public function add_fee_manually($e_id = FALSE,$a ='')
	{
		if(is_numeric($e_id) AND $this->authlink->verify_authlink($a))
		{
			if($this->input->post('manual_add_fee') !== FALSE)
			{

				$e_id_post = $this->input->post('enrollment_id');
				
				$this->view_data['enrollment_id'] 	= $e_id_post;
				
				$c_spr_id = $this->M_student_payment_record->current_payment_record_id($e_id_post);
					
				$counter =0;
				foreach($this->input->post('fee') as $key => $value)
				{
					foreach($value as $rate => $name)
					{
						$data[$counter]['sef_fee_name'] = $name;
						$data[$counter]['sef_fee_rate'] = $rate;
						$data[$counter]['sef_enrollment_id'] = $e_id_post;
						$data[$counter]['sef_gperiod_id'] = $this->current_grading_period;
						$data[$counter]['sef_schoolyear_id'] = $this->current_school_year;
						$data[$counter]['sef_created'] =NOW;
						$data[$counter]['is_other_fee'] = 1;
							
						if($c_spr_id !== NULL)
						{
							$for_pb[$counter]['spb_fee_name'] =$name;
							$for_pb[$counter]['spb_remaining_balance'] = $rate;
							$for_pb[$counter]['spb_fee_rate'] =$rate;
							$for_pb[$counter]['spb_transacted_by'] =$this->session->userdata('userid');
							$for_pb[$counter]['spb_spr_id'] =$c_spr_id;
							$for_pb[$counter]['spb_created'] =NOW;
							$for_pb[$counter]['spb_stud_enrollment_id'] = $e_id_post;
							$for_pb[$counter]['spb_is_other_fee'] = 1;
						}else{
							$for_pb = FALSE;
						}		
						$counter++;
					}
					
				}
				
				if($this->M_enrollees->cashier_add_new_fees($data,$for_pb) == TRUE){
					$this->authlink->clear_authlink();
					$this->_msg('s','Fees were successfully added.','fees/view_fees/'.$e_id_post);
				}else{
					$this->authlink->clear_authlink();
					$this->_msg('e','Fees were not added. Error encountered.','fees/view_fees/'.$e_id_post);
				}
			
			}else{
				$this->load->model('M_fees');
				$this->view_data['available_fees'] = $this->M_enrollees->get_available_fees($e_id);
				$this->view_data['enrollment_id'] = $e_id;
				$this->view_data['a'] = $a;
			}
		}else{
			redirect('fees/view_fees/'.$e_id);
		}
	}
	
	public function add_payment_record($enrollment_id = FALSE,$authlink = FALSE)
	{
		// if($this->M_enrollees->verify_if_approved_by_registrar($enrollment_id) == TRUE)
		$this->load->model('M_scholarships');
		if(in_array($this->session_user,$this->config->item('auth_recieve_payment'))){
			$this->view_data['enrollee_data'] = $enrollee_data = $this->M_enrollees->get_enrollee_prof($enrollment_id);
			if($enrollment_id != FALSE || $authlink != FALSE){
			$this->view_data['payee'] = $this->M_payee->get_payee($enrollee_data->profile_id);
			}else{
			$this->view_data['payee'] = FALSE;
			}
			$this->view_data['amount_due'] = $this->session->userdata('payment_data');
			$this->view_data['current_time'] = date('m/d/Y');
			$this->view_data['other_total'] = $this->M_enrollees->get_sum_of_student_electives($enrollment_id);
			$this->view_data['student_payment_schedule'] = $student_payment_schedules = $this->M_payment_mode_value->get_student_payment_schedule($enrollment_id);
			$student_payments = $this->M_payment_mode_value->get_student_enrollment_fees($enrollment_id);
			$this->view_data['misc_total'] = $this->M_enrollees->get_sum_of_student_miscelaneous($enrollment_id);
				
			$total_tuit = 0.00;
			$total_matr = 0.00;
			if($student_payments){
				foreach ($student_payments as $student_payment) {
					if($student_payment->is_tuition_fee == 1){
						$total_tuit += $student_payment->sef_fee_rate;
					}
					if($student_payment->is_cca_fee == 1){
						$total_matr += $student_payment->sef_fee_rate;
					}
				}
			}

			$this->view_data['total_tuit'] = $total_tuit;
			$this->view_data['total_matr'] = $total_matr;

			$c_spr_id = $this->M_student_payment_record->current_payment_record_id($enrollment_id);

			if($c_spr_id){
				$this->load->model('M_student_payment_breakdown','mspb');
				$electives = $this->mspb->get_specific_payment_breakdown_by_spr_id($enrollment_id,'other');
				$type='spb';
			}else{
				$this->load->model('M_enrollees','me');
			    $electives = $this->me->get_student_fees($enrollment_id,'','other');
				$type='sef';
			}
			
			
			
			
			//FOR STUDENT OVER THE COUNTER PAYMENTS
			$this->view_data['otcp'] = $this->M_enrollees->get_otcp($enrollment_id);
			$this->view_data['payment_modes'] = $this->M_enrollees->get_student_payment_mode($enrollment_id);
			$this->view_data['others'] = $electives;	
			$this->view_data['type'] = $type;
			$this->view_data['total_stud_deductions'] = $this->M_scholarships->sum_all_student_deductions($enrollment_id);
			
			if($enrollment_id == FALSE OR $authlink == FALSE){
				if($this->input->post('add_payment_record') !== FALSE){
					$enrollment_id_post = $this->input->post('enrollment_id');
					$authlink_post = $this->input->post('authlink');
					
					//if($this->M_enrollees->verify_if_approved_by_registrar($enrollment_id_post) == TRUE)
					//{								
						if($this->form_validation->run('add_payment_record') == FALSE){
							$this->view_data['enrollment_id'] = $enrollment_id_post;
							$this->view_data['authlink'] = $authlink_post;
						}else{
							// vaerify authlink, anti spam or XSS
							if($this->authlink->verify_authlink($authlink_post) == TRUE)
							{
								$input['spr_user_trans_id'] = $this->session->userdata('userid');
								$input['spr_user_trans_name'] = $this->session->userdata('username');
								$input['spr_enrollment_id'] = $enrollment_id_post;
								$input['spr_or_no'] = $this->input->post('spr_or_no');
								$input['spr_remarks'] = $this->input->post('remarks');
								$input['spr_payment_date'] =  date('Y-m-d',strtotime($this->input->post('date_of_payment')));
								$input['spr_schoolyear_id'] = $this->current_school_year;// defined in mycontroller
								$input['spr_gperiod_id'] = $this->current_grading_period;// defined in mycontroller
								$input['spr_ammt_paid'] = $this->input->post('ammount_paid');
								$input['spr_for_the_month_of'] = $this->input->post('month');
								$input['spr_mode_of_payment'] = $this->input->post('payment_type');
								$input['spr_created'] = NOW;
								$input['cheque_no'] = $this->input->post('cheque_no');
								$input['cheque_no'] = $this->input->post('credit_card_no');
								$input['cheque_no'] = $this->input->post('credit_card_name');

								if($this->M_student_payment_record->add_payment_record($input) == FALSE)
								{
									$this->authlink->clear_authlink();

									$this->_msg('e','Payment Record was not added.','fees/view_fees/'.$enrollment_id_post);
								}else{	
									if($this->M_student_payment_record->update_enrollment_record($enrollment_id_post) == TRUE){
										//$this->load->model('M_for_enrollment_id');
										//$this->load->library('idno_creator');
										//$generated_studentid = $this->idno_creator->generate_id();
										//$generated_id = $this->M_for_enrollment_id->check_id_generation($enrollment_id_post);
										//if($generated_id == FALSE){
											//update student number
											//$data['e_student_id'] = $generated_id;
											//$data['id_generated'] = 1;

											//$this->db->where('e_id', $enrollment_id_post);
											//$this->db->update('enrollments', $data); 
										//}else{
											//$sql = "SELECT for_e_id
											//		FROM for_enrollment_id 
											//		LIMIT 1";
											//$query = $this->db->query($sql);
											//if( $query->num_rows() >=1 ){
											//	$r = $query->row();
											//	$v = $r->for_e_id;
											//	$tempv = $v-1;
											//	$data_for_id['for_e_id'] = $tempv;
											//	$this->db->truncate('for_enrollment_id');
											//	$this->db->insert('for_enrollment_id', $data_for_id);
											//}
										//}
										
										$this->_msg('s','Payment Record was successfully added.','fees/payment_breakdown/'.$enrollment_id_post.'/'.$authlink_post);
									}else{
										$this->authlink->clear_authlink();
										$this->_msg('e','Payment Record was not added.','fees/view_fees/'.$enrollment_id_post);
									}
								}
							}else{
								$this->authlink->clear_authlink();
								$this->_msg('e','Token Expired','fees/view_fees/'.$enrollment_id_post);						
							}
						}
					//}else{
						//$this->authlink->clear_authlink();
						//$this->_msg('e','Enrollee Is not yet verified by the registrar.','fees/view_fees/'.$enrollment_id_post);
					//}
				}else{
					redirect($this->current_session_user);
				}
			}else{
				if($this->authlink->verify_authlink($authlink) == TRUE){
					$misc_fees = $this->M_enrollees->get_enrollee_fees($enrollment_id,$this->current_school_year,'misc');
					$tuit_fees = $this->M_enrollees->get_enrollee_fees($enrollment_id,$this->current_school_year,'tuit');
					$matr_fees = $this->M_enrollees->get_enrollee_fees($enrollment_id,$this->current_school_year,'cca');
					
					if(!empty($misc_fees) AND !empty($tuit_fees) AND !empty($matr_fees)){
						$this->view_data['enrollment_id'] = $enrollment_id;
						$this->view_data['authlink'] = $authlink;
					}else{
						$this->_msg('e','Warning, cannot add Payment Report. Tuition, Matriculation And Miscellaneous Fees must be set before adding Payment Record.','fees/view_fees/'.$enrollment_id);
					}
				}else{
					redirect('fees/view_fees/'.$enrollment_id);
				}		
			}
		}else{
			$this->_msg('e','Warning, cannot add Payment Report. You are not authorized to add payment record to student.','fees/view_fees/'.$enrollment_id);
		}
	}
	
	
	public function delete_stud_fee($sef_id = FALSE,$e_id = FALSE,$auth = FALSE)
	{
		if(!is_numeric($e_id) OR !is_numeric($sef_id) OR $auth == FALSE)
		{
			redirect($this->current_session_user);
		}else{
			if($this->authlink->verify_authlink($auth) == TRUE)
			{
				if($this->M_enrollees->delete_stud_fee($sef_id,$e_id) == TRUE)
				{	
					$this->_msg('s','The selected fees were successfully deleted.','fees/view_fees/'.$e_id);
				}else{
					$this->_msg('e','Selected fees were not deleted. An error was encountered. Please try again.','fees/view_fees/'.$e_id);
				}
			}else
			{
				redirect('fees/view_fees/'.$e_id);
			}
		}
	}
	
	public function check_fees($e_id = FALSE,$l_id = FALSE,$auth = FALSE)
	{
		if(($e_id == FALSE AND !(int)$e_id) OR ($l_id == FALSE AND !(int)$l_id) OR $auth == FALSE)
		{	
			if($this->input->post('check_fee_add') !== FALSE)
			{
				$e_id_post = $this->input->post('enrollment_id');
				$counter =0;
				foreach($this->input->post('fee') as $key => $value)
				{
					foreach($value as $rate => $name)
					{
							$data[$counter]['sef_fee_name'] = $name;
							$data[$counter]['sef_fee_rate'] = $rate;
							$data[$counter]['sef_enrollment_id'] = $e_id_post;
							$data[$counter]['sef_gperiod_id'] = $this->current_grading_period;
							$data[$counter]['sef_schoolyear_id'] = $this->current_school_year;
							$data[$counter]['sef_created'] =NOW;
							$data[$counter]['is_other_fee'] =1;
							$counter++;
					}
				}
				
				if($this->M_enrollees->cashier_add_new_fees($data) == TRUE){
					$this->authlink->clear_authlink();
					$this->session->set_flashdata('system_message','<div class="success">Fees were successfully added.</div>');
					redirect('fees/view_fees/'.$e_id_post);
				}else{
					$this->authlink->clear_authlink();
					$this->session->set_flashdata('system_message','<div class="error">Fees were not added.</div>');
					redirect('fees/view_fees/'.$e_id_post);
				}				
			}else
			{
				redirect($this->current_session_user);
			}
		}else
		{
			if($this->authlink->verify_authlink($auth) == TRUE)
			{
				$this->view_data['fees'] = $this->M_enrollees->check_level_fee_status($l_id);
				$this->view_data['e_id'] = $e_id;
				$this->view_data['l_id'] = $l_id;
				$this->view_data['authlink'] = $auth;
			}else
			{
				redirect($this->current_session_user);
			}
		}
	}

	
	function deductions($e_id='',$auth = FALSE)
	{
		if(is_numeric($e_id))
		{
			$this->load->model('M_scholarships','m');
			$this->view_data['enrollment_id'] = $e_id;
			$this->view_data['auth'] = $auth;
			$this->view_data['scholarships'] = $this->m->get_scholarships_available_for_stud($e_id);
			$this->view_data['system_message'] = $this->session->flashdata('system_message');
			
			if($this->input->post('add_scholarship'))
			{
			
				$this->form_validation->set_rules('scholarships','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('remarks','Remarks','trim|alpha_numeric|htmlspecialchars');
				
				if($this->form_validation->run() !== FALSE)
				{
					$data['scholarships'] = $this->input->post('scholarships');
					$data['remarks'] = $this->input->post('remarks');
					$data['enrollment_id'] = $e_id;
					if($this->m->get_selected_scholarship_and_insert_to_deductions($data))
					{
						$this->authlink->clear_authlink();
						$this->session->set_flashdata('system_message','<div class="success">Scholarship added to student.</div>');
					}else{
						$this->authlink->clear_authlink();
						$this->session->set_flashdata('system_message','<div class="error">Failed to add scholarship to student.</div>');
					}

					redirect('fees/view_fees/'.$e_id);
				}
			}
			
			if($this->input->post('add_deduction'))
			{
				echo 'add deduction';
			}
		}
	}
	
	public function payment_breakdown($enrollment_id,$a)
	{
		if($this->authlink->verify_authlink($a) == TRUE)
		{
			$e_id = intval($enrollment_id);
			$this->load->model(array('M_enrollees','M_student_payment_record'));
			$this->view_data['system_message'] = $this->session->flashdata('system_message');
			$this->view_data['enrollee_data'] = $this->M_enrollees->get_enrollee_prof($enrollment_id);
			
			$this->view_data['other_fees'] = $this->M_enrollees->get_enrollee_fees($e_id,$this->current_school_year,'other');
			$this->view_data['tuit_fees'] = $this->M_enrollees->get_enrollee_fees($e_id,$this->current_school_year,'tuit');
			$this->view_data['misc_fees'] = $this->M_enrollees->get_enrollee_fees($e_id,$this->current_school_year,'misc');
			$this->view_data['elec_fees'] = $this->M_enrollees->get_enrollee_fees($e_id,$this->current_school_year,'elec');
			$this->view_data['cca_fees'] = $this->M_enrollees->get_enrollee_fees($e_id,$this->current_school_year,'cca');
			
			
			$payment_id = $this->M_enrollees->get_latest_payment_record_id($e_id);
			
			$this->view_data['payment_record'] = $this->M_student_payment_record->get_payment_record($payment_id);
			
			$this->view_data['enl_id'] = $e_id;
			$this->view_data['pay_id'] = $payment_id;
			$this->view_data['authlink'] = $a;
			
			if($this->input->post('save_payment_breakdown'))
			{
				$data = $this->input->post('fee');
				$mpb = $this->input->post('max_payment_breakdown');
				$this->load->model('M_student_payment_breakdown','mspb');
		
				$result = $this->mspb->insert_payment_breakdown($data,$mpb);
				if($result->status == true)
				{
					$this->authlink->clear_authlink();
					$this->logger('log','User: {'.$fname.' '.$lname.'}, successfully breakdown payment for enrollment id {'.$e_id.'}.');
					$this->_msg('s',$result->log,'fees/view_fees/'.$enrollment_id);
				}else{
					$this->logger('log','User: {'.$fname.' '.$lname.'}, failed to breakdown payment for enrollment id {'.$e_id.'}.');
					$this->view_data['system_message'] = '<div class="alert alert-box">'.$result->log.'</div>';
				}
			}
		}else
		{
			redirect($this->current_session_user);
		}
	}
	
	public function delete_payment($eid,$id,$a)
	{
		if($this->authlink->verify_authlink($a) AND is_numeric($id) AND is_numeric($eid))
		{
			$this->load->model('M_student_payment_record','mspr');
			
			if($this->mspr->current_payment_record_id($eid) == $id)
			{
				if($this->mspr->delete_student_payment_and_record($id))
				{
					$this->authlink->clear_authlink();
					$this->_msg('s','Payment Was Successfully Deleted.','fees/payment_record/'.$eid);
				}else{
					$this->authlink->clear_authlink();
					$this->_msg('e','Unable to delete the payment record.','fees/payment_record/'.$eid);
				}
			}else{
				$this->authlink->clear_authlink();
				$this->_msg('e','Wrong payment record selected.','fees/payment_record/'.$eid);
			}
			
		}else{
			redirect($this->current_session_user);
		}
	}
	
	public function edit_payment($hash = '')
	{
		$x = $this->hs->decrypt($hash);
		if($x)
		{
			$eid = $x[0];
			$pid = $x[1];
			$this->load->model('M_student_payment_record','mspr');
			
			// pd($this->mspr->current_payment_record_id($eid).' '.$pid);
			if($this->mspr->current_payment_record_id($eid) == $pid)
			{
				$this->view_data['edit_amount'] = TRUE;
				$this->view_data['payment'] = $this->mspr->get_payment_record($pid);
				$this->view_data['enrollee_data'] = $this->M_enrollees->get_enrollee_prof($eid);
				$this->view_data['eid'] = $eid;
				$this->view_data['pid'] = $pid;
				$this->view_data['aut'] = $hash;

				if($this->input->post('update_payment_record'))
				{
					$input['spr_payment_date'] = date('Y-m-d',strtotime($this->input->post('date_of_payment')));
					$input['spr_ammt_paid'] = $this->input->post('amount_paid');
					$input['spr_remarks'] = $this->input->post('remarks');
					$input['spr_for_the_month_of'] = $this->input->post('month_of');
					$input['spr_mode_of_payment'] = $this->input->post('mde');
					
					if($this->mspr->update_payment_record($input,$pid))
					{
						$this->_msg('s','Payment Record was updated. Please update Breakdown of Payment.','fees/update_payment_breakdown/'.$hash);
					}else{
						$this->_msg('e','Unable to update payment record.','fees/edit_payment/'.$hash);
					}
				}
			}elseif($this->mspr->payment_record_ids($eid,$pid))
			{
				$this->view_data['edit_amount'] = TRUE;
				$this->view_data['payment'] = $this->mspr->get_payment_record($pid);
				$this->view_data['enrollee_data'] = $this->M_enrollees->get_enrollee_prof($eid);
				$this->view_data['eid'] = $eid;
				$this->view_data['pid'] = $pid;
				$this->view_data['aut'] = $hash;

				if($this->input->post('update_payment_record'))
				{
					$input['spr_payment_date'] = date('Y-m-d',strtotime($this->input->post('date_of_payment')));
					$input['spr_ammt_paid'] = $this->input->post('amount_paid');
					$input['spr_remarks'] = $this->input->post('remarks');
					$input['spr_for_the_month_of'] = $this->input->post('month_of');
					$input['spr_mode_of_payment'] = $this->input->post('mde');
					
					if($this->mspr->update_payment_record($input,$pid))
					{
						$this->_msg('s','Successfully updated payment record. Please update Breakdown of Payment.','fees/update_payment_breakdown/'.$hash);
					}else{
						$this->_msg('e','Unable to update payment record.','fees/edit_payment/'.$hash);
					}
				}
			}else{
				show_404();
			}
		}else{
			show_404();
		}
	}
	
	public function update_payment_breakdown($hash)
	{
		$x = $this->hs->decrypt($hash);
		$this->disable_browser_cache = TRUE;
		if($x)
		{
			$eid = $x[0];
			$pid = $x[1];

			$this->load->model('M_student_payment_breakdown','mspb');
			$this->load->model('M_enrollees','m_enrolle');
			
			$this->view_data['payment_record'] = $this->M_student_payment_record->get_payment_record($pid);
			$this->view_data['enrollee_data'] = $this->M_enrollees->get_enrollee_prof($eid);
			$tuit_pbd = $this->mspb->get_specific_breakdown($pid,$eid,'tuit');
			$cca_pbd = $this->mspb->get_specific_breakdown($pid,$eid,'cca');
			$misc_pbd = $this->mspb->get_specific_breakdown($pid,$eid,'misc');
			$other_pbd = $this->mspb->get_specific_breakdown($pid,$eid,'other');
			$this->view_data['tuit_fees'] = $tuit_pbd ? $tuit_pbd:$this->m_enrolle->get_enrollee_fees($eid,$this->current_school_year,'tuit');
			$this->view_data['cca_fees'] = $cca_pbd ? $cca_pbd:$this->m_enrolle->get_enrollee_fees($eid,$this->current_school_year,'cca');
			$this->view_data['misc_fees'] = $misc_pbd ? $misc_pbd:$this->m_enrolle->get_enrollee_fees($eid,$this->current_school_year,'misc');
			$this->view_data['other_fees'] = $other_pbd ? $other_pbd:$this->m_enrolle->get_enrollee_fees($eid,$this->current_school_year,'other');
			//$this->view_data['tuit_fees'] = $this->mspb->get_specific_breakdown($pid,$eid,'tuit');
			//$this->view_data['elec_fees'] = $this->mspb->get_specific_breakdown($pid,$eid,'elec');
			$this->view_data['pay_id'] = $pid;
			$this->view_data['enl_id'] = $eid;
			$this->view_data['auth'] = $hash;

			if($this->input->post('save_payment_breakdown'))
			{	
				$post_data = $this->input->post('fee');
				if($this->mspb->update_payment_breakdown($post_data,$pid,$eid))
				{
					$this->_msg('s','Successfully updated payment breakdown.','fees/payment_record/'.$eid);
				}else{
					$this->_msg('e','Unable to save changes.','fees/update_payment_breakdown/'.$hash);
				}
			}
		}else{
			$this->_msg('n','Wrong Link','fees/payment_record/'.$eid);
		}
	}
	
	
	public function add_uniform_fee($id = FALSE)
	{
		if($id !== FALSE AND is_numeric($id))
		{
			if($this->input->post('add_uniform'))
			{
				$fee_id = $this->input->post('uniform_fee_id');
				$fee_qty =$this->input->post('uniform_quantity');
				
				$this->load->model('M_fees','mf');
				$ufee = $this->mf->get_all_fees($fee_id);

				$c_spr_id = $this->M_student_payment_record->current_payment_record_id($id);
				
				$name = $ufee[0]->fee_desc.' - ('.$fee_qty.') PCS'; //name of fee and number of quantity
				$rate = ($ufee[0]->fee_rate * $fee_qty); // rate is rate of fee multiplied by quantity 
				
				$data['sef_fee_name'] = $name;
				$data['sef_fee_rate'] = $rate;
				$data['sef_enrollment_id'] = $id;
				$data['sef_gperiod_id'] = $this->current_grading_period;
				$data['sef_schoolyear_id'] = $this->current_school_year;
				$data['sef_created'] =NOW;
				$data['is_uniform_fee'] = 1;
					
				if($c_spr_id !== NULL)
				{
						$for_pb['spb_fee_name'] =$name;
						$for_pb['spb_remaining_balance'] = $rate;
						$for_pb['spb_fee_rate'] = $rate;
						$for_pb['spb_transacted_by'] =$this->session->userdata('userid');
						$for_pb['spb_spr_id'] =$c_spr_id;
						$for_pb['spb_created'] = NOW;
						$for_pb['spb_stud_enrollment_id'] = $enrollment_id_post;
						$for_pb['is_uniform_fee'] = 1;
				}else{
					$for_pb = FALSE;
				}
				
				if($this->M_enrollees->cashier_add_new_ufees($data,$for_pb) == TRUE)
				{
					$this->_msg('s','Uniform was successfully added to student.','fees/view_fees/'.$id);
				}else{
					$this->_msg('e','An error occured while adding uniform fee to student!','fees/view_fees/'.$id);
				}

			}else{
				show_error('Sorry Wrong Address,',404);
			}
		}else{
			show_error('Sorry Wrong Address,',404);
		}
	}
	
	
	public function p($id,$a='')
	{
		
		// pd($this->mpf->get_student_fees($id));
		if(is_numeric($id) AND $this->authlink->verify_authlink($a))
		{
			$this->load->model(array('M_school_settings','M_student','M_scholarships','M_enrollees'));
			$this->load->library(array('mpdf'));
			$this->load->helper('misc');
			$query = $this->M_school_settings->get_all_school_setting();
			$schoolyear_date = $this->schoolyear_date;
			$student = $this->M_student->get_student($id);
			$student_deduction = $this->M_scholarships->get_student_deductions($id);
			$student_scholarships = $this->M_scholarships->get_student_scholarships_deducted($id);
			$total_stud_deductions = $this->M_scholarships->sum_all_student_deductions($id);
			$tuit_fees = $this->M_enrollees->get_student_fees($id,$this->current_school_year,'tuit');
			$cca_fees = $this->M_enrollees->get_student_fees($id,$this->current_school_year,'cca');
			$misc_fees = $this->M_enrollees->get_student_fees($id,$this->current_school_year,'misc');
			$other_fees = $this->M_enrollees->get_student_fees($id,$this->current_school_year,'other');
			$payment_value = $this->M_enrollees->get_student_payment_mode($e_id);
			$sum_paid_fees = $this->M_enrollees->get_sum_of_paid_fees($id,$this->current_school_year);
			$sum_amount_due = $this->M_enrollees->get_sum_of_amount_due($id,$this->current_school_year);
			$payment_mode = $this->M_enrollees->get_student_payment_mode($id);
			if(!empty($query) AND !empty($student))
			{
				$data['school_name'] = $query->school_name;
				$data['school_address'] = $query->school_address;
				$data['school_telephone'] = $query->school_telephone;
				$data['school_mobile'] = $query->school_mobile;
				$data['school_website'] = $query->school_website;
				$data['school_email'] = $query->school_email;
				$data['schoolyear_date'] = $schoolyear_date;
				$data['student'] = $student;
				$data['student_deduction'] = $student_deduction;
				$data['student_scholarships'] = $student_scholarships;
				$data['total_stud_deductions'] = $total_stud_deductions;
				$data['tuit_fees'] = $tuit_fees;
				$data['cca_fees'] = $cca_fees;
				$data['misc_fees'] = $misc_fees;
				$data['misc_fees'] = $misc_fees;
				$data['other_fees'] = $other_fees;
				$data['payment_value'] = $payment_value;
				$data['sum_paid_fees'] = $sum_paid_fees;
				$data['sum_amount_due'] = $sum_amount_due;
				$data['payment_mode'] = $payment_mode;

				$html = $this->load->view('print_pdf_layouts/print_student_fee',$data,TRUE);
				
				$filename = 'View Fees:'.ucwords(strtolower($student->firstname)).' '.ucwords(strtolower($student->middlename)).' '.ucwords(strtolower($student->lastname)).' '.ucwords(strtolower($student->name_ext));
				$mpdf=new mPDF('c','LETTER','','' , 0 , 0 , 0 , 0 , 0 , 0);
				$mpdf->SetDisplayMode('fullpage');
				$mpdf->list_indent_first_level = 0;  // 1 or 0 - whether to indent the first level of a list
				$mpdf->WriteHTML($html);
				$mpdf->Output($filename,'I');
			}else{
				show_404();
			}
		}else{
			redirect($this->current_session_user);
		}
	}
	
	public function _process_student_deduction($e_id,$data)
	{
		return $this->M_scholarships->process_student_deduction($e_id,$data);
	}
	
	private function _process_student_scholarship($student_id = FALSE,$scholarship_id = FALSE)
	{
	
		// vd(is_numeric($student_id) AND is_numeric($scholarship_id));
		if(is_numeric($student_id) AND $scholarship_id)
		{
			$this->load->model('M_scholarships','ms');
			//if($this->ms->_check_payment_mode($student_id))
			//{
				foreach($scholarship_id as $value)
				{
					//set time limit process may take long
					set_time_limit(0);
					$flag[] = $this->ms->insert_and_process_student_scholarship($student_id,$value);
				}
				
				
				if(count(array_unique($flag)) === 1)  
				{
					return (object)['status'=>TRUE,'message'=>'Successfully Applied Scholarship Package to Student.'];
				}else{
					return (object)['status'=>FALSE,'message'=>'Unable to applay Scholarship Package to student.'];
				}
				
			//}else{
				//return (object)array('status'=>FALSE,'message'=>'Please apply payment plan, before adding scholarship to student.');
			//}
		}else{
			show_error('System Error!, Command Not Found.',404);
		}
	}
	
	public function delete_deduction($hash = '')
	{
		$x = $this->hs->decrypt($hash);
		if($x)
		{
			$this->load->model('M_scholarships','ms');
			$e_id = $x[0];
			$d_id = $x[1];
			if($this->ms->_delete_deduction($e_id,$d_id))
			{
				$this->_recompute_fee_alone($e_id);
				$fname = $this->session->userdata('e_f_name');
				$lname = $this->session->userdata('e_l_name');
				$this->logger('log','User: {'.$fname.' '.$lname.'}, successfully deleted deduction for enrollment id {'.$e_id.'}.');
				$this->_msg('s','Successfully deleted deduction and recalculated fees.','fees/view_fees/'.$e_id);
			}else{
				$this->_recompute_fee_alone($e_id);
				$fname = $this->session->userdata('e_f_name');
				$lname = $this->session->userdata('e_l_name');
				$this->logger('log','User: {'.$fname.' '.$lname.'}, failed to delete deduction for enrollment id {'.$e_id.'}.');
				$this->_msg('e','An error was encountered. Unable to delete and process deduction.','fees/view_fees/'.$e_id);
			}
		}else{
			show_404();
		}
	}
	
	public function edit_deduction($hash = '')
	{
		$x = $this->hs->decrypt($hash);
		if($x)
		{
			$this->load->model('M_scholarships','ms');
			$e_id = $x[0];
			$d_id = $x[1];
			$this->view_data['enrollment_id'] = $e_id;
			$this->view_data['deduction'] = $this->ms->get_student_deduction($e_id,$d_id);
			
			if($this->input->post('update_deduction'))
			{
				$this->form_validation->set_rules('deduction_rate','Deduction Rate','trim|numeric|required');
				$this->form_validation->set_rules('deduction_desc','Deduction Description','trim|strtolower|required');
				
				if($this->form_validation->run() !== FALSE)
				{
					$post['sdr_amount'] = $this->input->post('deduction_rate');
					$post['sdr_remarks'] = $this->input->post('deduction_desc');
					if($this->ms->_update_deduction($post,$d_id))
					{
						$this->_recompute_fee($e_id);
						$fname = $this->session->userdata('e_f_name');
						$lname = $this->session->userdata('e_l_name');
						$this->logger('log','User: {'.$fname.' '.$lname.'}, successfully updated deduction for enrollment id {'.$e_id.'}.');
						$this->_msg('s','Successfully updated deduction and recalculated fees.','fees/view_fees/'.$e_id);
					}else{
						$this->_recompute_fee($e_id);
						$fname = $this->session->userdata('e_f_name');
						$lname = $this->session->userdata('e_l_name');
						$this->logger('log','User: {'.$fname.' '.$lname.'}, failed to update deduction for enrollment id {'.$e_id.'}.');
						$this->_msg('e','An error was encountered. Unable to update and process deduction.','fees/view_fees/'.$e_id);
					}
				}else{
					$this->view_data['system_message'] = validation_errors() == '' ? NULL : $this->_msg('e',validation_errors()); 
				}
			}
		}else{
			show_404();
		}
	}
	
	public function payment_center()
	{
		if(in_array($this->session_user,$this->config->item('auth_recieve_payment')))
		{
			$this->load->library('token');
			$this->token->set_token();
			$this->view_data['token'] = $this->token->get_token();
			$this->view_data['current_time'] = date('m/d/Y');
			$this->view_data['overvalidationerror'] = $this->_msg(FALSE,FALSE,FALSE,'overthecounter');
			
			$this->view_data['items'] = $this->M_fees->get_other_fees();
			
			
			if($this->input->post('add_payment_record'))
			{
				if($this->token->validate_token($this->input->post('loc_sdi')))
				{
				
					$this->form_validation->set_rules('student','Student ID','required|trim|htmlspecialchars');
					$this->form_validation->set_rules('spr_or_no','OR Number','required|trim|htmlspecialchars');
					$this->form_validation->set_rules('ammount_paid','Amount','required|trim|htmlspecialchars|numeric');
					$this->form_validation->set_rules('date_of_payment','Payment Date','required|trim|datechecker|htmlspecialchars');
					$this->form_validation->set_rules('remarks','remarks','trim|htmlspecialchars');
					$this->form_validation->set_rules('loc_sdi','Invalid Token','required|trim|htmlspecialchars');
					
					if($this->form_validation->run() !== FALSE)
					{
						$student_e_id = $this->M_enrollees->check_id_number($this->input->post('student'));

						if($student_e_id !== FALSE)
						{
						
							$misc_fees = $this->M_enrollees->check_student_set_fees($student_e_id,$this->current_school_year,'misc');
							$tuit_fees = $this->M_enrollees->check_student_set_fees($student_e_id,$this->current_school_year,'tuit');
							$other_fees = $this->M_enrollees->check_student_set_fees($student_e_id,$this->current_school_year,'other');
							
							if($misc_fees AND $tuit_fees AND $other_fees)
							{
								$input['spr_user_trans_id'] = $this->session->userdata('userid');
								$input['spr_user_trans_name'] = $this->session->userdata('username');
								$input['spr_enrollment_id'] = $student_e_id;
								$input['spr_or_no'] = $this->input->post('spr_or_no');
								$input['spr_remarks'] = $this->input->post('remarks');
								$input['spr_payment_date'] =  date('Y-m-d',strtotime($this->input->post('date_of_payment')));
								$input['spr_schoolyear_id'] = $this->current_school_year;// defined in mycontroller
								$input['spr_gperiod_id'] = $this->current_grading_period;// defined in mycontroller
								$input['spr_ammt_paid'] = $this->input->post('ammount_paid');
								$input['spr_created'] = NOW;
								
								if($this->M_student_payment_record->add_payment_record($input) == FALSE)
								{
									$authlink = $this->authlink->generate_authlink();
									$this->_msg('e','Payment record was not added.','fees/payment_center#payment-center-one');
								}else
								{	
									if($this->M_student_payment_record->update_enrollment_record($student_e_id) == TRUE)
									{
										$authlink = $this->authlink->generate_authlink();
										$this->_msg('s','Payment record was successfully added.','fees/payment_breakdown/'.$student_e_id.'/'.$authlink);
									}else{
										$this->authlink->clear_authlink();
										$this->_msg('e','Payment record was not added.','fees/payment_center#payment-center-one');
									}
								}
							}else{
								$link = '<a href="'.site_url('fees/view_fees/'.$student_e_id).'" class="btn btn-mini">Set Student Fee</a>';
								$message = 'An error has occured. Fee has not been set for this student. Please set student fees by clicking the link '.$link.'.';
								$this->_msg('p',$message,'fees/payment_center#payment-center-one');
							}
						
						}else{
							$this->_msg('e','Error student ID Number not in system records.','fees/payment_center#payment-center-one');
						}
					}else{
						$this->view_data['structuredvalidationerror'] = $this->_msg('e',validation_errors());
					}
				}else{
					$this->_msg('e','Submit failed form token Expired. Please try again.','fees/payment_center#payment-center-one');
				}
			}
			
			/*
				For Over tHE coUNTER KINDS OF FEES
			*/
			
			if($this->input->post('over_the_counter'))
			{
				if($this->token->validate_token($this->input->post('loc_sdi')))
				{
					$this->form_validation->set_rules('student','Student ID','required|trim|htmlspecialchars');
					$this->form_validation->set_rules('spr_or_no','OR Number','required|trim|htmlspecialchars');
					$this->form_validation->set_rules('quantity[]','Quantity','required|is_numeric|trim|htmlspecialchars');
					// $this->form_validation->set_rules('price[]','Unit Price','required|is_numeric|trim|htmlspecialchars|numeric');
					$this->form_validation->set_rules('date_of_payment','Payment Date','required|trim|datechecker|htmlspecialchars');
					$this->form_validation->set_rules('desc[]','Description','required|trim|htmlspecialchars');
					$this->form_validation->set_rules('loc_sdi','Invalid Token','required|trim|htmlspecialchars');
					
					if($this->form_validation->run() !== FALSE)
					{
						$student_e_id = $this->M_enrollees->check_id_number($this->input->post('student'));

						if($student_e_id !== FALSE)
						{
							// $quan  = $this->input->post('quantity');
							// $desc  = $this->input->post('desc');
							// $price = $this->input->post('price');
							$post = $this->input->post();
							
							// foreach($price as $k => $v)
							// {
								// $input[$k]['quantity'] = $quan[$k];
								// $input[$k]['remarks'] = $desc[$k];
								// $input[$k]['ammt_paid'] = number_format($v * $quan[$k],'2','.',',');
								// $input[$k]['user_trans_id'] = $this->session->userdata('userid');
								// $input[$k]['user_trans_name'] = $this->session->userdata('username');
								// $input[$k]['enrollment_id'] = $student_e_id;
								// $input[$k]['or_no'] = $this->input->post('spr_or_no');
								// $input[$k]['payment_date'] =  date('Y-m-d',strtotime($this->input->post('date_of_payment')));
								// $input[$k]['schoolyear_id'] = $this->current_school_year;// defined in mycontroller
								// $input[$k]['gperiod_id'] = $this->current_grading_period;
								// $input[$k]['created'] = NOW;
							// }
							
							if($this->M_student_payment_record->over_the_counter_payments($post,$student_e_id) == FALSE)
							{
								$this->authlink->clear_authlink();
								$this->_msg('e','Payment record was not added.','fees/payment_center#payment-center-two');
							}else
							{	
								$this->_msg('s','Added payment record.','fees/payment_center#payment-center-two');
							}
						}else{
							$this->_msg('e','Error student ID Number not in system records.','fees/payment_center#payment-center-two');
						}
					}else{
						//show validation errors on view
						$this->_msg('e',validation_errors(),'fees/payment_center#payment-center-two','overthecounter');
					}
				}else{
					$this->_msg('e','Token already expired. Please try again.','fees/payment_center#payment-center-two');
				}
			}
			
		}else{
			show_404();
		}
	}

	public function registration_fee($e_id)
	{

		$this->load->library('token');
		$this->token->set_token();
			
		if($this->input->post('add_payment_record')){
			if($this->token->validate_token($this->input->post('loc_sdi'))){
				
				//$this->form_validation->set_rules('student','Student ID','trim|htmlspecialchars');
				$this->form_validation->set_rules('spr_or_no','OR Number','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('ammount_paid','Amount','required|trim|htmlspecialchars|numeric');
				$this->form_validation->set_rules('date_of_payment','Payment Date','required|trim|datechecker|htmlspecialchars');
				$this->form_validation->set_rules('payment_type','Type of Payment','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('remarks','remarks','trim|htmlspecialchars');
				$this->form_validation->set_rules('loc_sdi','Invalid Token','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('section_id', 'Section Assignment', 'required|trim|htmlspecialchars');
					
				if($this->form_validation->run() !== FALSE){

						if($e_id !== FALSE)
						{
							$input['spr_user_trans_id'] = $this->session->userdata('userid');
							$input['spr_user_trans_name'] = $this->session->userdata('username');
							$input['spr_enrollment_id'] = $e_id;
							$input['spr_or_no'] = $this->input->post('spr_or_no');
							$input['spr_remarks'] = $this->input->post('remarks')=='' ? $this->input->post('remarks') : 'Reservation Fee';
							$input['spr_payment_date'] =  date('Y-m-d',strtotime($this->input->post('date_of_payment')));
							$input['spr_schoolyear_id'] = $this->current_school_year;// defined in mycontroller
							$input['spr_gperiod_id'] = $this->current_grading_period;// defined in mycontroller
							$input['spr_for_the_month_of'] = 'Reservation';
							$input['spr_ammt_paid'] = $this->input->post('ammount_paid');
							$input['cheque_no'] = $this->input->post('cheque_no');
							$input['credit_card_no'] = $this->input->post('credit_card_no');
							$input['credit_card_name'] = $this->input->post('credit_card_name');
							$input['spr_created'] = NOW;
								
							if($this->M_student_payment_record->add_payment_record($input) == FALSE){
								$authlink = $this->authlink->generate_authlink();
								$this->_msg('e','Payment record was not added.','fees/registration_fee/'.$e_id);
							}else{	
								//if($this->M_student_payment_record->update_enrollment_record($e_id) == TRUE){
									$this->M_enrollees->assign_student_section($e_id, $this->input->post('section_id'));
									$authlink = $this->authlink->generate_authlink();
									$this->_msg('s','Payment record was successfully added.','search/applicants');
								//}else{
								//	$this->authlink->clear_authlink();
								//	$this->_msg('e','Payment record was not added.','fees/registration_fee/'.$e_id);
								//}
							}
							
						}else{
							$this->_msg('e','Error, student not in system records.','search/applicants');
						}
				}else{
					$this->view_data['structuredvalidationerror'] = $this->_msg('e',validation_errors());
				}
			}else{
				$this->_msg('e','Submit failed form token Expired. Please try again.','search/applicants');
			}
		}

		$this->view_data['token'] = $this->token->get_token();
		$this->view_data['current_time'] = date('m/d/Y');
		$this->view_data['overvalidationerror'] = $this->_msg(FALSE,FALSE,FALSE,'registration_fee');
		$this->view_data['student'] = $this->M_student->get_student($e_id);
		$this->view_data['sections'] = $this->M_sections->get_section_by_grade_level_array($this->view_data['student']->level_id);
		$this->view_data['payee'] = $payee = $this->M_payee->get_payee($this->view_data['student']->profile_id);
	}
	
	public function set_payment_mode($id = FALSE,$auth = FALSE)
	{
		if(is_numeric($id) AND $this->authlink->verify_authlink($auth))
		{
		
			// pd($id);
		
			$this->load->model('M_fees','mf');
			$this->load->model('M_payment_mode','mpm');
			$this->load->model('M_payment_mode_value','mpmv');
			$this->load->library('token');
			$this->token->set_token();
			
			$this->view_data['enrollee_data'] = $profile = $this->M_enrollees->get_enrollee_prof($id);
			$enrollment_data = $this->M_enrollees->get_enrollee_profile_all($profile->profile_id);
			$this->view_data['payment_modes'] = $this->mf->payment_plans($enrollment_data->level_id);
			$this->view_data['payment_values'] = $payment_values = $this->mf->payment_plan_values($enrollment_data->level_id);
			$this->view_data['selected_payment_mode'] = $selected_payment_mode = $this->M_enrollees->get_student_payment_mode($id);
			$this->view_data['selected_payment_mode_value'] = $selected_payment_mode_value = $this->M_enrollees->get_student_payment_mode_value($id);
			$this->view_data['auth'] = $auth;
			$this->view_data['token'] = $this->token->get_token();
			$this->view_data['id'] = $id;
			$this->view_data['level_id'] = $enrollment_data->level_id;
			
			if($this->input->post('set_student_payment_mode'))
			{
				if($this->token->validate_token($this->input->post('stpr_loc')))
				{
					$this->form_validation->set_message('required','Please choose one from the payment modes below.');
					$this->form_validation->set_rules('selected_payment_mode','Payment Mode','required|trim');
					if($this->form_validation->run() == FALSE)
					{
						$this->view_data['system_message'] = $this->_msg('e',validation_errors());
					}else{
						
						//if($selected_payment_mode != $this->input->post('selected_payment_mode')){

							if($this->input->post('selected_payment_mode')=='none'){

								$payment_mode_name = 'cash basis';
								$payment_mode_value = $this->mf->get_payment_plan_values($payment_mode_name,$enrollment_data->level_id);

								if($payment_mode_value === FALSE){
									$this->_msg('e','Unable to update payment mode. Payment mode value not set.','fees/view_fees/'.$id);
								}else{
									if($payment_mode_value->payment_plan_tuit==0.00 || $payment_mode_value->payment_plan_matr==0.00){
										$this->_msg('e','Unable to update payment mode. Payment mode value not set.','fees/view_fees/'.$id);
									}else{

										$enroll_data['payment_mode'] = $payment_mode_name;

										//call model
										$payment_plan_id = $this->mpm->get_payment_plan_id($payment_mode_name);
										$tuit = $this->mpmv->get_payment_plan_tuit($enrollment_data->level_id,$payment_plan_id->id);
										$matr = $this->mpmv->get_payment_plan_matr($enrollment_data->level_id,$payment_plan_id->id);

										if(floatval($matr->payment_plan_matr)!=0.00 && floatval($tuit->payment_plan_tuit)!=0.00){
											if(strtolower($payment_mode_name=='cash basis')){
												$newtuit = floatval ($tuit->payment_plan_tuit) * 1.00;
												$newmatr = floatval ($matr->payment_plan_matr) * 1.00;

												$data = array(
   																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'Registration',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																)
																);
											}

											//update tuition and matriculation
											$sql = "UPDATE student_enrollment_fees 
															SET sef_fee_rate = ?
															WHERE sef_enrollment_id = ? AND 
															is_tuition_fee = 1";
											$this->db->query($sql,array($newtuit,$id));

											$sql = "UPDATE student_enrollment_fees 
															SET sef_fee_rate = ?
															WHERE sef_enrollment_id = ? AND 
															is_cca_fee = 1";
											$this->db->query($sql,array($newmatr,$id));

											$this->db->where('e_id', $id);
											$this->db->update('enrollments', $enroll_data); 

											$this->db->delete('student_payment_schedules', array('sps_e_id' => $id)); 

											$this->db->insert_batch('student_payment_schedules', $data); 

											$this->_msg('s','Payment mode updated.','fees/view_fees/'.$id);

										}else{
											$this->_msg('e','Unable to update payment mode. Values for Tuition and Matriculation are equal to zero.','fees/view_fees/'.$id);
										}
									}
								}
							}else{
								$payment_mode_name = $this->input->post('selected_payment_mode');
								$payment_mode_value = $this->mf->get_payment_plan_values($payment_mode_name,$enrollment_data->level_id);

								if($payment_mode_value === FALSE){
									$this->_msg('e','Unable to update payment mode. Payment mode value not set.','fees/view_fees/'.$id);
								}else{
									if($payment_mode_value->payment_plan_tuit==0.00 || $payment_mode_value->payment_plan_matr==0.00){
										$this->_msg('e','Unable to update payment mode. Payment mode value not set.','fees/view_fees/'.$id);
									}else{

										$enroll_data['payment_mode'] = $payment_mode_name;

										//call model
										$payment_plan_id = $this->mpm->get_payment_plan_id($payment_mode_name);
										$tuit = $this->mpmv->get_payment_plan_tuit($enrollment_data->level_id,$payment_plan_id->id);
										$matr = $this->mpmv->get_payment_plan_matr($enrollment_data->level_id,$payment_plan_id->id);

										if(floatval($matr->payment_plan_matr)!=0.00 && floatval($tuit->payment_plan_tuit)!=0.00){
											if(strtolower($payment_mode_name=='cash basis')){
												$newtuit = floatval ($tuit->payment_plan_tuit) * 1.00;
												$newmatr = floatval ($matr->payment_plan_matr) * 1.00;

												$data = array(
   																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'Registration',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																)
																);
											}
											if(strtolower($payment_mode_name=='2- payment plan')){
												$newtuit = floatval ($tuit->payment_plan_tuit) * 2.00;
												$newmatr = floatval ($matr->payment_plan_matr) * 2.00;

												$data = array(
   																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'Registration',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'October',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																)
																);
											}
											if(strtolower($payment_mode_name=='4- payment plan')){
												$newtuit = floatval ($tuit->payment_plan_tuit) * 4.00;
												$newmatr = floatval ($matr->payment_plan_matr) * 4.00;

												$data = array(
   																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'Registration',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'August',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'October',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'December',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																)
																);
											}
											if(strtolower($payment_mode_name=='9- payment plan')){
												$newtuit = floatval ($tuit->payment_plan_tuit) * 9.00;
												$newmatr = floatval ($matr->payment_plan_matr) * 9.00;

												$data = array(
   																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'Registration',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'July',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'August',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'September',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'October',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'November',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'December',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'January',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																),
  																array(
      															'sps_e_id' => $id ,
      															'sps_pm_id' => $payment_plan_id->id,
      															'sps_month' => 'Febuary',
      															'sps_tuition' => $tuit->payment_plan_tuit,
      															'sps_matri' => $matr->payment_plan_matr
  																)
																);
											}

											//update tuition and matriculation
											$sql = "UPDATE student_enrollment_fees 
															SET sef_fee_rate = ?
															WHERE sef_enrollment_id = ? AND 
															is_tuition_fee = 1";
											$this->db->query($sql,array($newtuit,$id));

											$sql = "UPDATE student_enrollment_fees 
															SET sef_fee_rate = ?
															WHERE sef_enrollment_id = ? AND 
															is_cca_fee = 1";
											$this->db->query($sql,array($newmatr,$id));

											$this->db->where('e_id', $id);
											$this->db->update('enrollments', $enroll_data); 

											$this->db->delete('student_payment_schedules', array('sps_e_id' => $id)); 

											$this->db->insert_batch('student_payment_schedules', $data); 

											$this->_msg('s','Payment mode updated.','fees/view_fees/'.$id);

										}else{
											$this->_msg('e','Unable to update payment mode. Values for Tuition and Matriculation are equal to zero.','fees/view_fees/'.$id);
										}
										/*
										$data['payment_mode_value'] = $payment_mode_value = $payment_mode_value->payment_plan_amount;
										$result = $this->mf->set_student_payment_mode($id,$data);
											
										if($result)
										{
											if(strtolower($payment_mode_name=='cash basis')){
												$newtuit = $payment_mode_value;
											}
											
											if(strtolower($payment_mode_name=='2- payment plan')){
												$newtuit = $payment_mode_value * 2;
											}
											if(strtolower($payment_mode_name=='4- payment plan')){
												$newtuit = $payment_mode_value * 4;
											}
											if(strtolower($payment_mode_name=='9- payment plan')){
												$newtuit = $payment_mode_value * 9;
											}
											
											$sql = "UPDATE student_enrollment_fees 
													SET sef_fee_rate = ?
													WHERE sef_enrollment_id = ? AND 
													is_tuition_fee = 1";
											$this->db->query($sql,array($newtuit,$id));
											
											$this->_msg('s','Payment mode updated.','fees/view_fees/'.$id);
										}else{
											$this->_msg('e','Unable to update payment mode.','fees/view_fees/'.$id);
										}*/
									}
								}
							}

							
						
							

						
						
						
							
						//}else{
							//$this->_msg('s','No new data to save.','fees/view_fees/'.$id);
						//}
					}
				}else{
					$this->token->destroy_token();
					$this->_msg('e','Invalid form token.','fees/set_payment_mode/'.$id.'/'.$auth);
				}
			}
		}else{
			show_error('Unable to process you request, invalid entry give to parameters, please don\'t mess with the URL',404);
		}                                        
	}
	
	public function payment_group()
	{
		$this->load->model('M_payment_group','pg');
		$this->view_data['payment_groups'] = $this->pg->get_group();
		$this->view_data['system_message'] = $this->_msg();
		
		if($this->input->post('create_payment_group'))
		{
			$this->form_validation->set_rules('group_name','','trim|strip_tags');
			$this->form_validation->set_rules('group_desc','','trim|strip_tags');
			
			$input = $this->input->post();
		
			if($this->pg->set_group($input))
			{
				$this->_msg('s','Payment Group Added','fees/payment_group#view-payment-group');
			}else{
				$this->_msg('s','Payment Group Added','fees/payment_group#new-payment-group');
			}
		}
	}
	
	public function view_payment_group($r_id)
	{
		$this->view_data['system_message'] = $this->_msg();
		$x = $this->hs->decrypt($r_id);
		if($x)
		{
			$id = $x[0];
			$this->load->model('M_payment_group','pg');
			$this->view_data['payment_group_desc'] = $this->pg->get_group($id);
			
			$this->view_data['hash_id'] = $r_id;
			$this->view_data['raw_id'] = $id;
			$this->view_data['set_cca'] = $this->pg->get_set_fee('cca',$id);
			$this->view_data['set_tuit'] =$this->pg->get_set_fee('tuit',$id); 
			$this->view_data['set_misc'] = $this->pg->get_set_fee('misc',$id);
			

			$this->view_data['cca'] = $this->pg->get_array('cca');
			$this->view_data['tuit'] = $this->pg->get_array('tuit');
			$this->view_data['misc'] = $this->pg->get_array('misc');
			$this->view_data['slevels'] = $this->pg->get_selected_grade_level($id);
			$this->view_data['ulevels'] = $this->pg->get_unselected_grade_level();


			
			if($this->input->post('create_payment_group_fees'))
			{
				
				$this->form_validation->set_rules('misc','Miscellaneous Fee','required|trim|strip_tags');
				$this->form_validation->set_rules('tuit','Tuition Fee','required|trim|strip_tags');
				$this->form_validation->set_rules('cca','CCA Fee','required|trim|strip_tags');
				
				if($this->form_validation->run() === FALSE)
				{
					$this->view_data['system_message'] = validation_errors() == '' ? NULL : $this->_msg('e',validation_errors());
				}else{				
					$post = $this->input->post();
					if($this->pg->create_payment_group_fees($post,$id))
					{

						$this->_msg('s','Payment Group Fees Set','fees/view_payment_group/'.$r_id);
					}else{
						$this->_msg('s','Payment Group Fees Set','fees/view_payment_group/'.$r_id);
					}
				}
			}
			
			if($this->input->post('set_payment_group_grade_level'))
			{
				$post = $this->input->post();
				unset($post['set_payment_group_grade_level']);

				if(!empty($post))
				{
					if($this->pg->set_grade_levels($post,$id))
					{
						$this->_msg('s','Grade Level Updated','fees/view_payment_group/'.$r_id);
					}else{
						$this->_msg('e','Unable to update grade level','fees/view_payment_group/'.$r_id);
					}
				}else{
					$this->_msg('n','Cannot update empty grade level.','fees/view_payment_group/'.$r_id);
				}
			}
		}else{
			$this->_msg('n','Unable to process requested URL.','fees/payment_group');
		}
	}
	
	public function clear_payment_group_fees($r_id)
	{
		$this->view_data['system_message'] = $this->_msg();
		$x = $this->hs->decrypt($r_id);
		
		if($x)
		{
			$id = $x[0];
			$this->load->model('M_payment_group','pg');
			if($this->pg->reset_group_fees($id))
			{
				$this->_msg('s','Reset Group Fee was successful.','fees/view_payment_group/'.$r_id);
			}else{
				$this->_msg('e','Unable to reset Fees.','fees/view_payment_group/'.$r_id);
			}
		}else{
			$this->_msg('e','Unable to reset Fees.','fees/view_payment_group/'.$r_id);
		}
	}
	
	public function remove_level_from_group($r_id,$g_id)
	{
		$this->view_data['system_message'] = $this->_msg();
		$x = $this->hs->decrypt($r_id);
		
		if($x)
		{
			$id = $x[0];
			$this->load->model('M_payment_group','pg');
			$raw = $this->hs->encrypt($x[1]);
			if($this->pg->remove_level_from_group($id))
			{
				$this->_msg('s','Grade level is removed from group.','fees/view_payment_group/'.$g_id);
			}else{
				$this->_msg('e','Unable to remove grade level from group.','fees/view_payment_group/'.$g_id);
			}
			
			
		}else{
			$this->_msg('e','Unable to remove grade level from group.','fees/view_payment_group/'.$g_id);
		}
	}
	
	
	
	public function foreign_fees()
	{
		$this->view_data['system_message'] = $this->_msg();
		$this->load->model(array('M_fees','M_levels'));
		$this->view_data['levels'] = $this->M_fees->get_foreign_fees();
		$this->view_data['levels_dropd'] = $this->M_levels->get_all_levels_array();
		//$this->view_data['fees_dropd'] = $this->M_fees->get_op_fees();

		if($this->input->post('apply_foreign_fee'))
		{
			//$this->form_validation->set_rules('level','Grade Level','trim|required');
			$this->form_validation->set_rules('add_foreign_price','Foreign Fee Rate','trim|required|numeric');
			if($this->form_validation->run() !== FALSE)
			{
				$post = $this->input->post();
				if($this->M_fees->update_foreign_fees($post) === TRUE)
				{
					$this->_msg('s','Successfully updated foreign.','fees/foreign_fees#set-foreign');
				}else{
					$this->_msg('e','Unable to update foreign fee.','fees/foreign_fees#set-foreign');
				}
			}else{
				$this->view_data['system_message'] = $this->_msg('e',validation_errors());
			}
		}
	}
	
	public function delete_foreign_fees($id)
	{
		$x = $this->hs->decrypt($id);
		
		if($x)
		{
			if($this->M_fees->delete_foreign_fee_from_level_list($x[0]))
			{
				$this->_msg('s','Foreign Fee was deleted from grade level.','fees/foreign_fees#view-foreign');
			}else{
				$this->_msg('e','Unable to delete Foreign Fee from grade level.','fees/foreign_fees#view-foreign');
			}
		}else{
			$this->_msg('e','Unable to process requested URL.','fees/foreign_fees#view-foreign');
		}
	}
	
	public function edit_foreign_fees($id)
	{
		$x = $this->hs->decrypt($id);
		
		$this->view_data['current_fee'] = $this->M_fees->get_foreign_fee_from_level_list($x[0]);
		$this->load->model(array('M_fees','M_levels'));
		$this->view_data['levels'] = $this->M_fees->get_foreign_fees();
		$this->view_data['levels_dropd'] = $this->M_levels->get_all_levels_array();
		
		if($x)
		{
			if($this->input->post('update_foreign_fee'))
			{
				$this->form_validation->set_rules('add_foreign_price','Foreign Fee Rate','trim|required|numeric');
				if($this->form_validation->run() !== FALSE)
				{
					$post = $this->input->post();
					if($this->M_fees->update_foreign_fees($post) === TRUE)
					{
						$this->_msg('s','Successfully updated foreign fee to Grade Level.','fees/foreign_fees#view-foreign');
					}else{
						$this->_msg('e','Unable to update foreign fee to Grade Level.','fees/foreign_fees#view-foreign');
					}
				}else{
					$this->view_data['system_message'] = $this->_msg('e',validation_errors());
				}
			}
		}else{
			$this->_msg('e','Unable to process requested URL','fees/foreign_fees#view-foreign');
		}
	}
	
	public function billing_form($hash_id = '')
	{
		$x = $this->hs->decrypt($hash_id);
		if($x)
		{
			$e_id = $x[0];
			
			// vd($this->session->userdata);
			$this->load->model('M_fees','mf');
			$this->load->model('M_student','ms');
			$this->load->model('M_student_payment_record','mspr');
			$this->load->model('M_billing_form','mbf');
			
			$this->view_data['bill_to'] = $sd = $this->ms->get_student($e_id);
			$c_spr_id = $this->mspr->current_payment_record_id($e_id);

			if($c_spr_id)
			{
				$this->load->model('M_student_payment_breakdown','mspb');
				$electives = $this->mspb->get_specific_payment_breakdown_by_spr_id($c_spr_id,'elec');
				$type='spb';
			}else{
				$this->load->model('M_enrollees','me');
			    $electives = $this->me->get_student_fees($e_id,'','elec');
				$type='sef';
			}
			
			if($this->input->post('generate_billing_form'))
			{
				$post = $this->input->post();
				$res = $this->mbf->create_billing_form($post,$e_id);
				
				if($res->stat == TRUE)
				{
					$this->_msg('s',$res->log,'fees/billing_form/'.$hash_id.'#show-billing-form');
				}else{
					$this->_msg('s',$res->log,'fees/billing_form/'.$hash_id.'#create');
				}
			}
			
			$this->view_data['others'] = $electives;
			$this->view_data['type'] = $type;
			$this->view_data['id'] = $e_id;
			$this->view_data['hash_id'] = $hash_id;
			$this->view_data['student_billing_form'] = $this->mbf->get_student_billings($e_id);
			$this->view_data['fees_for_billing'] = $this->mbf->get_fees_for_data($e_id,$sd->level_id);
			$this->view_data['payment_modes'] = $this->mf->get_student_current_payment_mode_and_due_by_enrollment_id($e_id);
			$this->view_data['bill_to'] = $this->ms->get_student($e_id);
			
		}else{
			show_error('Unable to proccess requested page, Broken link Found',404);
		}
	}
	
	public function billing_form_edit($hash = '')
	{
		$x = $this->hs->decrypt($hash);
		
		if($x)
		{
			$e_id = $x[0];
			$b_id = $x[1];
			
			$this->load->model('M_billing_form','mbf');
			$this->load->model('M_student','ms');
			$sd = $this->ms->get_student($e_id);
			$this->view_data['fees_for_billing'] = $this->mbf->get_fees_for_data($e_id,$sd->level_id);
			$this->view_data['bfd'] = $this->mbf->get_specific_billing_form($b_id);
			$this->view_data['bill_to'] = $this->ms->get_student($e_id);
			$this->view_data['hash_id'] = $hash;
			
			if($this->input->post('update_billing_form'))
			{
				$post = $this->input->post();
				
				$res = $this->mbf->_update_billing_form($post,$b_id);
			
				if($res === TRUE)
				{
					$this->_msg('s','Changes were saved','fees/billing_form_edit/'.$hash);
				}else{
					$this->_msg('e','Unable to save changes. Error Occured.','fees/billing_form_edit/'.$hash);
				}
			}
		}else{
			show_404();
		}
	}
	
	public function sort_by_payment_modes()
	{
		$this->load->model('M_fees');
		$this->view_data['annual'] = $this->M_fees->get_payment_mode_by_category('annual');
		$this->view_data['semestral'] = $this->M_fees->get_payment_mode_by_category('semestral');
		$this->view_data['trimester'] = $this->M_fees->get_payment_mode_by_category('trimester');
		$this->view_data['monthly'] = $this->M_fees->get_payment_mode_by_category('monthly');
	}
	
	public function items()
	{
		$this->load->model('M_fees');
		// $this->view_data['other_fees'] = $this->M_fees->
	}
	
	public function delete_items_from_billing($hash = '',$ohash = FALSE)
	{
		$x = $this->hs->decrypt($hash);
		$y = $this->hs->decrypt($ohash);
		if($x AND $y)
		{
			$id = $x[0];
			$this->db->where('id',$id)->limit(1)->delete('student_billing_items');
			if($this->db->affected_rows() >=1)
			{
				$this->_msg('s','Item was successfully deleted.','fees/billing_form_edit/'.$ohash);
			}else{
				$this->_msg('e','Unable to delete item. Try again.','fees/billing_form_edit/'.$ohash);
			}
		}else{
			show_404();
		}
	}

	public function recompute_fee($hash = '')
	{
		$x = $this->hs->decrypt($hash);
		if($x)
		{
			$e_id = $x[0];
			// $c_spr_id = $this->M_student_payment_record->current_payment_record_id($e_id);
			$res = $this->_recompute_fee($e_id);
			if($res)
			{
				$this->_msg('s','Re-computation of student fee was successful.','fees/view_fees/'.$e_id);
			}else{
				$this->_msg('e','Unable to recompute student Fees.','fees/view_fees/'.$e_id);
			}
		}else{
			show_404();
		}
	}
	
	/*+----------------
	  | Recomputes Student Fees
	  +----------------
	*/
	private function _recompute_fee($e_id)
	{
		//delete student enrollment fees by enrollment id because we will insert a new one.
		// this is better than updating the old fees, much faster

		$this->db->where('sef_enrollment_id',$e_id)
						 ->where('sef_schoolyear_id',$this->current_school_year)
						 ->where('is_elective_fee !=', 1)
						 ->where('is_other_fee !=', 1)
						 ->delete('student_enrollment_fees');
		
		//generate student fees
		$this->load->model('M_level_fees','mlf');
			
		$res = $this->mlf->generate_student_fees($e_id);
		
		if($res->stat == 'true')
		{
			//recalculate tuition and miscelaneous fee according to payment plan
			$this->load->model('M_payment_mode','mpm');
			$this->load->model('M_payment_mode_value','mpmv');

			$selected_payment_mode = $this->M_enrollees->get_student_payment_mode($e_id);
			$enrollment_data = $this->M_enrollees->get_enrollee_prof($e_id);
			$payment_plan_id = $this->mpm->get_payment_plan_id($selected_payment_mode->payment_mode);
			
			$tuit = $this->mpmv->get_payment_plan_tuit($enrollment_data->level_id,$payment_plan_id->id);
			$matr = $this->mpmv->get_payment_plan_matr($enrollment_data->level_id,$payment_plan_id->id,$this->current_school_year);
			
			if(floatval($matr->payment_plan_matr)!=0.00 && floatval($tuit->payment_plan_tuit)!=0.00){
				if(strtolower($selected_payment_mode->payment_mode=='cash basis')){
					$newtuit = floatval ($tuit->payment_plan_tuit) * 1.00;
					$newmatr = floatval ($matr->payment_plan_matr) * 1.00;
				}
				if(strtolower($selected_payment_mode->payment_mode=='2- payment plan')){
					$newtuit = floatval ($tuit->payment_plan_tuit) * 2.00;
					$newmatr = floatval ($matr->payment_plan_matr) * 2.00;
				}
				if(strtolower($selected_payment_mode->payment_mode=='4- payment plan')){
					$newtuit = floatval ($tuit->payment_plan_tuit) * 4.00;
					$newmatr = floatval ($matr->payment_plan_matr) * 4.00;
				}
				if(strtolower($selected_payment_mode->payment_mode=='9- payment plan')){
					$newtuit = floatval ($tuit->payment_plan_tuit) * 9.00;
					$newmatr = floatval ($matr->payment_plan_matr) * 9.00;
				}

				//update tuition and matriculation
				$sql = "UPDATE student_enrollment_fees 
								SET sef_fee_rate = ?
								WHERE sef_enrollment_id = ? AND 
								is_tuition_fee = 1";
				$this->db->query($sql,array($newtuit,$e_id));

				$sql = "UPDATE student_enrollment_fees 
								SET sef_fee_rate = ?
								WHERE sef_enrollment_id = ? AND 
								is_cca_fee = 1";
				$this->db->query($sql,array($newmatr,$e_id));
			}
			//return true
			$this->_msg('s',$res->log,'fees/view_fees/'.$e_id);
		}else{
			//return false
			$this->_msg('e',$res->log,'fees/view_fees/'.$e_id);
		}


		return TRUE;
	}
	
	private function _recompute_fee_alone($e_id)
	{
		//delete student enrollment fees by enrollment id because we will insert a new one.
		// this is better than updating the old fees, much faster

		$this->db->where('sef_enrollment_id',$e_id)
						 ->where('sef_schoolyear_id',$this->current_school_year)
						 ->where('is_elective_fee !=', 1)
						 ->where('is_other_fee !=', 1)
						 ->delete('student_enrollment_fees');
		
		//generate student fees
		$this->load->model('M_level_fees','mlf');
			
		$res = $this->mlf->generate_student_fees($e_id);
		if($res->stat == 'true')
		{
			//recalculate tuition and miscelaneous fee according to payment plan
			$this->load->model('M_payment_mode','mpm');
			$this->load->model('M_payment_mode_value','mpmv');

			$selected_payment_mode = $this->M_enrollees->get_student_payment_mode($e_id);
			$enrollment_data = $this->M_enrollees->get_enrollee_prof($e_id);
			$payment_plan_id = $this->mpm->get_payment_plan_id($selected_payment_mode->payment_mode);
			
			$tuit = $this->mpmv->get_payment_plan_tuit($enrollment_data->level_id,$payment_plan_id->id);
			$matr = $this->mpmv->get_payment_plan_matr($enrollment_data->level_id,$payment_plan_id->id,$this->current_school_year);
			
			if(floatval($matr->payment_plan_matr)!=0.00 && floatval($tuit->payment_plan_tuit)!=0.00){
				if(strtolower($selected_payment_mode->payment_mode=='cash basis')){
					$newtuit = floatval ($tuit->payment_plan_tuit) * 1.00;
					$newmatr = floatval ($matr->payment_plan_matr) * 1.00;
				}
				if(strtolower($selected_payment_mode->payment_mode=='2- payment plan')){
					$newtuit = floatval ($tuit->payment_plan_tuit) * 2.00;
					$newmatr = floatval ($matr->payment_plan_matr) * 2.00;
				}
				if(strtolower($selected_payment_mode->payment_mode=='4- payment plan')){
					$newtuit = floatval ($tuit->payment_plan_tuit) * 4.00;
					$newmatr = floatval ($matr->payment_plan_matr) * 4.00;
				}
				if(strtolower($selected_payment_mode->payment_mode=='9- payment plan')){
					$newtuit = floatval ($tuit->payment_plan_tuit) * 9.00;
					$newmatr = floatval ($matr->payment_plan_matr) * 9.00;
				}

				//update tuition and matriculation
				$sql = "UPDATE student_enrollment_fees 
								SET sef_fee_rate = ?
								WHERE sef_enrollment_id = ? AND 
								is_tuition_fee = 1";
				$this->db->query($sql,array($newtuit,$e_id));

				$sql = "UPDATE student_enrollment_fees 
								SET sef_fee_rate = ?
								WHERE sef_enrollment_id = ? AND 
								is_cca_fee = 1";
				$this->db->query($sql,array($newmatr,$e_id));
			}
			//return true
			RETURN TRUE;
		}else{
			//return false
			RETURN FALSE;
		}


		return TRUE;
	}
	
	public function balance_report()
	{
		$this->load->model('M_levels','m');
		$this->load->model('m_payment_report','msr');
		$this->view_data['levels'] = $this->m->get_all_levels_array();

		if($this->input->get())
		{
			$get_vars = $this->input->get();

			if(isset($get_vars['levels']) AND 
			   isset($get_vars['type']) AND 
			   !empty($get_vars['levels']) AND 
			   !empty($get_vars['type']) AND in_array($get_vars['type'],['pdf','excel']))
			{

				if($this->hs->decrypt($get_vars['levels']))
				{
					if($get_vars['type'] == 'pdf')
					{
						redirect('pdf/balancereports/'.$get_vars['levels']);
					}elseif($get_vars['type'] == 'excel'){
						redirect('excel_gen/balancereports/'.$get_vars['levels']);
					}else{
						show_error('Unable to retrieve requested data.',404);
					}
				}
				
				show_error('Unable to retrieve requested data.',404);
			}else{
				show_error('Unable to retrieve requested data.',404);
			}
		}
	}
	
}